//
//  QBComposeViewController.swift
//  Wei91BoiOS
//
//  Created by bing on 16/3/30.
//  Copyright © 2016年 bing. All rights reserved.
//

import UIKit

import SVProgressHUD

class QBComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // model时需要背景颜色，不然是透明
        view.backgroundColor = UIColor.whiteColor()
        
        prepareUI()
        
        // 监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        print("viewDidAppear textView.inputView:\(textView.inputView)")
        
        textView.becomeFirstResponder()
    }
    
    /**
     {
         UIKeyboardAnimationCurveUserInfoKey = 7;
         UIKeyboardAnimationDurationUserInfoKey = "0.25";
         UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 224}}";
         UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 680}";
         UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 456}";
         UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 568}, {320, 224}}";
         UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 344}, {320, 224}}";
         UIKeyboardIsLocalUserInfoKey = 1;
     }}
     */
    
    func keyboardWillChangeFrame(notification: NSNotification) {
        
        //QBPrint(msg: "键盘将要改变:\(notification)")
        
        // 动画时间
        let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        
        // 目标frame
        let frame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]?.CGRectValue ?? CGRectZero
        // 计算toolBar底部间距
        let margin = -(UIScreen.height - frame.origin.y)
        
        // 更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(margin)
        }
        
        // 动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    private func prepareUI() {
        setupNavigationBar()
        setupTextView()
        setupPhotoSelector()
        setupToolBar()
        setupLengthTip()
    }
    
    /// 设置照片选择器
    private func setupPhotoSelector() {
        // 当一个控制器的view是另外一个控制器的view的子view，控制器也最好是父子关系
        let photoSelectorView = photoSelectorVC.view
        // 添加控件
        self.view.addSubview(photoSelectorView)
        // 将photoSelectorVC成为self的子控制器，这样事件传递才正常
        self.addChildViewController(photoSelectorVC)
        // 添加约束
        photoSelectorView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(view)
            make.height.equalTo(view).multipliedBy(0.6)
            // 先将照片选择器的view往下便宜自己的高度
            make.bottom.equalTo(view).offset(UIScreen.height * 0.6)
        }
    }
    
    /// 设置长度提示label
    private func setupLengthTip() {
        view.addSubview(statusLengthTipLabel)
        
        // 约束
        statusLengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(view).offset(-5)
            make.bottom.equalTo(toolBar.snp_top).offset(-5)
        }
    }
    
    /// 设置textView
    private func setupTextView() {
        // 添加控件
        view.addSubview(textView)
        // 让UIScrollView/子类自动适配,如果有导航栏就往下移动64
        /*
        automaticallyAdjustsScrollViewInsets:起效是有前提的
        1.UIScrollView/子类所在的控制器是在导航控制器里面
        2.UIScrollView/子类需要是控制器的view(UITableView)或者UIScrollView/子类是控制器view的第一个View,UIScrollView/子类是控制器的view的第一个子View的第一个子view
        
        */
        self.automaticallyAdjustsScrollViewInsets = true
        // 添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    }
    
    @objc private func picture() {
        //QBPrint(msg: "图片")
        // 隐藏键盘
        textView.resignFirstResponder()
        
        // 设置照片选择器的底部偏移为0
        photoSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(0)
        }
        
        UIView.animateWithDuration(QBDefaultDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    @objc private func trend() {
        QBPrint(msg: "#")
    }
    
    @objc private func mention() {
        QBPrint(msg: "@")
    }
    
    @objc private func emoticon() {
        //QBPrint(msg: "表情")
        // 切换系统键盘，当键盘显示的时候，设置textView.inputView是不会立马切换键盘的，系统在弹出键盘那一刻，来判断如果textView.inputView = nil,就弹出系统键盘，如果textView.inputView != nil，就弹出textView.inputView作为键盘
        // 在设置键盘之前将键盘退回去
        textView.resignFirstResponder()
        
        print("手动弹出前：\(textView.inputView)")
        // 设置键盘
        //textView.inputView = emoticonKeyboard

        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil

        // 将键盘弹出来，延迟0.25秒弹出键盘
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            
            self.textView.becomeFirstResponder()
        }
        print("手动弹出后：\(textView.inputView)")
    }
    
    @objc private func add() {
        QBPrint(msg: "加号")
    }
    
    private func setupToolBar() {
        // 添加到view
        view.addSubview(toolBar)
        
        //约束
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_add_background", "action": "add"]]
        
        // 创建空数组
        toolBar.items = [UIBarButtonItem]()
        
        var index = 0
        for dict in itemSettings {
            let imageName = dict["imageName"]!
            let action = dict["action"]!
            
            // Selector: 可以直接传入字符串,但是不能传入变量
            let item = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action))
            
            toolBar.items?.append(item)
            
            let button = item.customView
            button?.tag = index
            index++
            
            // 按钮后面添加弹簧
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 移除最后一个弹簧
        toolBar.items?.removeLast()
    }
    
    private func setupNavigationBar() {
        // 左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        // 右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        // 发送按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitleView()
    }
    
    private func setupTitleView() {
        let prefix = "发微博"
        
        if let name = QBUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            
            // 发微博Bing_John
            let text = prefix + "\n" + name
            let label = UILabel()
            
            // 设置
            label.textColor = UIColor.blackColor()
            label.font = UIFont.systemFontOfSize(13)
            label.textAlignment = NSTextAlignment.Center
            label.numberOfLines = 0
            
            // 设置文本属性
            let attr = NSMutableAttributedString(string: text)
            
            let nameRange = (text as NSString).rangeOfString(name)
            
            attr.addAttributes([NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSFontAttributeName: UIFont.systemFontOfSize(11)], range: nameRange)
            
            label.attributedText = attr
            // 注意sizeToFit需要在设置属性文本之后地调用
            label.sizeToFit()
            
            navigationItem.titleView = label
        } else {
            // 没有名称
            navigationItem.title = prefix
        }
    }
    // MARK: - 按钮点击事件
    /// 关闭控制器
    @objc private func dismiss() {
        SVProgressHUD.dismiss()
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发微博
    @objc private func send() {
        QBPrint(msg: "发微博")
        // 获取到输入的内容
        let status = textView.emoticonText()
        // 判断是否超出长度
        if QBComposeVCStatusMaxLength - status.characters.count < 0 {
            
            SVProgressHUD.showErrorWithStatus("微博内容超出最大长度")
            return
        }
        
        // 获取用户选择的第一张图片
        let image = photoSelectorVC.photos.first
        
        // 发微博
        SVProgressHUD.showWithStatus("正在发微博....", maskType: SVProgressHUDMaskType.Black)
        
        QBStatusViewModel.sharedInstance.sendStatus(status, image: image) { (error) -> () in
            
            if error != nil {
                QBPrint(msg: "发布微博失败:\(error)")
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            
            // 发布微博成功，延迟关闭
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.dismiss()
            })
        }
    }
    
    // MARK: - 懒加载
    /// toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()

    /*
        iOS输入控件:
        1.UITextField
        1.只能显示一行
        2.有占位文本
        3.继承UIControl,不能滚动的
        
        2.UITextView
        1.可以显示多行
        2.没有占位文本
        3.继承UIScrollView,可以滚动
    */
    private lazy var textView: QBPlaceholderTextView = {
        let textView = QBPlaceholderTextView()
        
        // 设置
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.blackColor()
        //textView.backgroundColor = UIColor.brownColor()
        // 弹簧效果
        textView.alwaysBounceVertical = true
        // 拖拽键盘退下
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.delegate = self
        
        textView.placehoder = "我是占位文本"
        
        return textView
    }()
    
    private lazy var emoticonKeyboard: QBEmoticonKeyboard = {
        let keyboard = QBEmoticonKeyboard()
        
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    /// 长度提示的label
    private lazy var statusLengthTipLabel: UILabel = {
        let label = UILabel()
        
        // 设置
        label.font = UIFont.systemFontOfSize(11)
        label.textColor = UIColor.lightGrayColor()
        label.text = String(QBComposeVCStatusMaxLength)
       
        
        return label
    }()
    
    /// 照片选择器
    /// 当一个控制器的view是另外一个控制器的view的子view, 控制器也最好是父子关系
    private lazy var photoSelectorVC: PhotoSelectorViewController = PhotoSelectorViewController()
}

extension QBComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        // 有文字
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
   
        // 获取文字的长度
        // QBPrint(msg:"textView.emoticonText(): \(textView.emoticonText())")
        let length = textView.emoticonText().characters.count
        
        let left = QBComposeVCStatusMaxLength - length
        
        statusLengthTipLabel.text = String(left)
        
        // 设置颜色
        statusLengthTipLabel.textColor = left < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
}
